package com.agent.crm.service;

import xu.ye.view.HomeContactActivity;
import android.annotation.SuppressLint;
import android.app.Service;
import android.content.AsyncQueryHandler;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.IBinder;
import android.provider.ContactsContract;

import com.agent.crm.config.AppConfig;
import com.agent.crm.db.DBInitScript;
import com.agent.crm.db.DatabaseManager;
import com.agent.crm.util.CnToSpell;

public class InitDataService extends Service {
	
	private DatabaseManager manager = null;
	private AsyncQueryHandler asyncQuery;
	SQLiteDatabase sqlLite ;

	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return null;
	}
	
	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
		if(null==manager){
			manager = new DatabaseManager(InitDataService.this);
		}
		sqlLite = manager.getWritableDatabase();
				// TODO Auto-generated method stub
		initContacts();
		
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		if(sqlLite.isOpen()){
			sqlLite.close();
		}
		if(manager != null){
	        manager.close();
	    }
		super.onDestroy();
	}

	@Override
	public void onStart(Intent intent, int startId) {
		// TODO Auto-generated method stub
		super.onStart(intent, startId);
	}

	/**
     * 数据库异步查询类AsyncQueryHandler
     * 
     * @author administrator
     * 
     */
    @SuppressLint("UseSparseArrays")
    private class MyAsyncQueryHandler extends AsyncQueryHandler {

        public MyAsyncQueryHandler(ContentResolver cr) {
            super(cr);
        }

        /**
         * 查询结束的回调函数
         */
		@Override
		protected void onQueryComplete(int token, Object cookie,
				final Cursor cursor) {
			// TODO Auto-generated method stub
			sqlLite.delete(DBInitScript.Table_ContactsInfo, null, null);
            new Thread(new Runnable() {
				
				@Override
				public void run() {
					// TODO Auto-generated method stub
					long start = System.currentTimeMillis();
					sqlLite.beginTransaction();
					ContentValues content = new ContentValues();
					if (cursor != null && cursor.getCount() > 0) {
						cursor.moveToFirst();
						for (int i = 0; i < cursor.getCount(); i++) {
							cursor.moveToPosition(i);
							String name = cursor.getString(1);
							String number = cursor.getString(2);
							System.out.println("===============123465=================="+i+"befoer change"+(System.currentTimeMillis()-start)/1000);
							String sortKey = CnToSpell.getFirstSpell(name);
							System.out.println("===============123465=================="+i+"after change"+(System.currentTimeMillis()-start)/1000);
							int contactId = cursor.getInt(3);
							Long photoId = cursor.getLong(4);
							String lookUpKey = cursor.getString(5);
							content.put("name", name);
							content.put("mobile_phone", number);
							content.put("sort_key", sortKey);
							content.put("lookup_key", lookUpKey);
							content.put("photoid", photoId);
							content.put("sys_contactid", contactId);
							content.put("is_attention", 0);
							sqlLite.insert(DBInitScript.Table_ContactsInfo, null,
									content);
							System.out.println("===============123465==================after insert"+i+"record"+(System.currentTimeMillis()-start)/1000);
						}
					}
					sqlLite.setTransactionSuccessful();
					sqlLite.endTransaction();
					cursor.close();
//					sqlLite.close();
					AppConfig.loadingFromMobileContacts = false;
					SharedPreferences preferences =getSharedPreferences("initData",Context.MODE_PRIVATE);
					Editor editor =preferences.edit();
					editor.putBoolean("initContacts", true);
					editor.commit();
					if(manager != null){
				        manager.close();
				    }
					System.out.println("===============123465==================after insert"+(System.currentTimeMillis()-start)/1000);
		            stopSelf();
				}
			}).start();
			
		}

    }
	
	public void initContacts() {
		// TODO Auto-generated method stub
		if(null==manager){
			manager = new DatabaseManager(InitDataService.this);
		}
		// manager.deleteDatabase(this);
//		SQLiteDatabase database = manager.getWritableDatabase();
		Cursor cursorContact = sqlLite.query(DBInitScript.Table_ContactsInfo,
				new String[] { "sys_contactid" }, null, null, null, null, null,
				null);
		if (null!=cursorContact&&!cursorContact.moveToFirst()) {
			AppConfig.loadingFromMobileContacts = true;
			asyncQuery = new MyAsyncQueryHandler(getContentResolver());
			asyncQuery.startQuery(0, null,
					ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
					HomeContactActivity.projection, null, null,
					"display_name COLLATE LOCALIZED asc"); // 按照sort_key升序查询
		}
		cursorContact.close();
//		sqlLite.close();
	}
}
